#! /usr/bin/env python
#coding=utf-8

#import psycopg2 as pg2
#import psycopg2.extras
#import sqlite3 as sqlite
#import os,time, hashlib
from Ini2Dict import Ini2Dict
i = Ini2Dict()
ini = i.GetDict() 
import MySQLdb
import datetime

class MySQL:
    
    def __init__(self, info):
        self.Error = "APP_SQL_Error"   
        self.conn = MySQLdb.connect (host = info[0],
                                    user = info[1],
                                    passwd = info[2],
                                    db = info[3],
                                    charset = info[4])
        self.cursor = self.conn.cursor (MySQLdb.cursors.DictCursor)
        
    def SQLQuery(self, sql):
        try:            
            self.cursor.execute(sql)
        except:
            from Log import Log
            l = Log()
            l.WriteEro(sql)

    def Lastrowid(self):
        return self.cursor.lastrowid
    
    def GetAll(self):
        try:            
            res = self.cursor.fetchall()
        except:
            return self.Error + "LinkSQL fetchall "
        if res != None:
            return self.T(res)
        return res
    
    def GetOne(self):
        try:
            res = self.cursor.fetchone()
        except:
            return self.Error
        if res != None:
            return self.T(res)        
        return res

    def T(self, res):        

        for m, e in enumerate(res):
            for s in e: 
                try:
                    if isinstance(e[s], datetime.datetime) or isinstance(e[s], datetime.date) or isinstance(e[s], datetime.time)  or isinstance(e[s], datetime.tzinfo):
                        res[m][s] = e[s].strftime('%Y-%m-%d  %H:%M:%S')
                    if isinstance(e[s], datetime.timedelta):
                        res[m][s] = str(e[s])
                except:
                    pass
        return res
    def Commit(self):
        self.conn.commit ()
        
    def DBClose(self):
        self.cursor.close ()
        self.conn.close ()        
    
class LinkSQL(MySQL):

    def __init__(self):
        global ini
        info = (ini["mhost"], ini["muser"], ini["mpasswd"], ini["mdbname"], ini["mchar"])
        MySQL.__init__(self, info)

    def CheckSQL(self, sql):
        pass
    
class LogSQL(MySQL):

    def __init__(self):
        global ini
        info = (ini["lhost"], ini["luser"], ini["lpasswd"],
                            ini["ldbname"], ini["lchar"])    
        MySQL.__init__(self, info) 

